package com.chen.service.handler;

import com.alibaba.fastjson.JSON;
import com.chen.model.entity.user.UserInfo;
import com.chen.service.util.AuthContextUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author cgj
 * @date 4/22/25 2:43 PM
 */
@Component
public class UserLoginInterceptor implements HandlerInterceptor {
    //  进入前处理, 都放行, 就是放行前加点东西
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取token
        String token = request.getHeader("token");
        //根据token从redis中获取用户信息
        String userJson = redisTemplate.opsForValue().get("user:login:" + token);
        UserInfo userInfo = JSON.parseObject(userJson, UserInfo.class);
        // 存放到threadLocal中
        AuthContextUtil.set(userInfo);
        return true;
    }

    /**
     * 在当前请求响应之前,清除信息.
     * 否则线程返回到线程池,有可能不被清除,在下一个请求来时,会保留上一个请求用户的信息,造成安全问题
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthContextUtil.remove();
    }
}
